(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];
    function init(o){
        $(document).click(function(){
            let thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                let str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                let ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    data: productInfo,
                    url:'initStock/add/getProductInfo',
                    cols: [[
                        {field: 'productCode', width: 120, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'},
                        {field: 'directoryName', width: 120, title: '产品目录'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    let data = obj.data;
                    let tableData = table.cache["storageproductstableid"];
                    $.each(tableData,function(index,value){
                        if(value.tempId == ids){
                            data.tempId = ids;
                            //美金采购价=[人民币采购价]/[人名币汇率]
                            let rmbRate = $("#rmbRate").val();
                            if(!checkNumber(rmbRate)){
                                rmbRate = 0;
                            }
                            let purchasePriceRmb = data.purchasePriceRmb;
                            if(!checkNumber(purchasePriceRmb)){
                                purchasePriceRmb = 0;
                            }
                            let purchasePriceUsd = 0;
                            if(0 != rmbRate){
                                purchasePriceUsd = new BigNumber(purchasePriceRmb).dividedBy(rmbRate).dp(4, BigNumber.ROUND_HALF_UP).toString();
                            }
                            data["purchasePriceUsd"] = purchasePriceUsd;
                            //金额小计（默认为零）
                            data["moneySubtotal"] = 0;
                            //利润额（默认为零）
                            data["profitMargin"] = 0;
                            //利润率（默认为零）
                            data["profitMarginRatio"] = 0;
                            //仓库费用金额（默认为零）
                            data["warehouseCostAmount"] = 0;
                            //40HQ海运费（默认为零）
                            data["fortyOceanFreight"] = 0;
                            //数量（默认为零）
                            data["productNum"] = 0;
                            //金额小计（默认为零）
                            data["moneySubtotal"] = 0;
                            //边际利润率（默认为零）
                            data["marginalProfitRatio"] = 0;
                            //海关相关信息
                            if(!isEmpty(data.customsCode)){
                                data = setHSInfo(data);
                            }
                            //配件相关信息
                            //产品编码
                            let productCode = data.productCode;
                            //规格编码
                            let specNo = data.specificationCode;
                            let tempPartsList = [];
                            if(!isEmpty(specNo)){
                                $.ajax({
                                    url: "offer/getProductPartsInfoBySpecNo?specNo=" + specNo + "&productCode=" + productCode,
                                    async:false,
                                    success:function(res){
                                        if(res.status == 200){
                                            for(let i in res.data){
                                                let partTempId = GenNonDuplicateID(3) + (index+1);
                                                res.data[i]["tempId"] = partTempId;
                                                res.data[i]["parentTempId"] = data.tempId;
                                                //成品比例(默认1)
                                                res.data[i]["proportionFinishedProducts"] = 1;
                                                //配件比例(默认1)
                                                res.data[i]["partsFinishedProducts"] = 1;
                                                tempPartsList.push(res.data[i]);
                                            }
                                        }else {
                                            layer.msg("获取信息失败，请稍后再试！", {icon: 5});
                                        }
                                    }
                                });
                            }
                            data["partsList"] = tempPartsList;

                            tableData[index] = data;
                        }
                    });
                    table.reload('storageproductstableid',{data:tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode == 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function(index, values){
            if(values.tempId == ids){
                tableData[index]["productCode"] = value;
                //$(".value_"+values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                info:value
            }});
    }
})(window.jQuery);

var form = layui.form, laydate = layui.laydate, partsParentTempId = "", customsCode =[], annexList = [], partsList = [], upload = layui.upload, table = layui.table, $ = layui.jquery, id = getQueryVariable("id");

layui.use(['tableEdit',"selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        selectInput = layui.selectInput;


    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    //客户信息
    let customerInfo = [];
    //客户所属业务员信息
    let salesmanInfo = [];
    //国家信息
    let country = [];
    //客户联系人
    let customerContact = [];
    //价格术语
    let priceTerms = [];
    //币种
    let currencyInfo = [];
    //美元编码
    let usdCode = "";
    //美元
    let usdName = "";
    //美金汇率
    let usdRate = "";
    //美金对人名币汇率
    let rmbRate = "";
    //公司信息
    let companyInfo = [];
    //收款银行信息
    let bankAccountList = [];
    //单位
    let unitOfQuantity = [];
    //费用类型
    let costType = [];
    let tempDetail = [];
    let newCostList = [];
    let tempAnnexList = [];
    //删除的老的附件ID集合
    let deleteAnnexIds = [];


    $(document).ready(function () {
        //1.获取所有下拉框信息
        getSelectData();

        //2.获取详情信息
        getDetailInfo();

        table.reload('storageproductstableid',{data:tempDetail});
        table.reload('costtableid',{data:newCostList});
        table.reload('attachmenttableid',{data:tempAnnexList});
    });


    function getDetailInfo() {
        //获取详情信息
        $.ajax({
            url:"offer/detail?id="+id,
            async:false,
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    if(null != res.data){
                        //主表数据
                        let vo =  res.data;

                        setCustomerInfo(vo.customerName);
                        $("#customerCode").val(vo.customerCode);
                        $("#customerName").val(vo.customerName);
                        $("#countryCode").val(vo.countryCode);
                        //获取客户联系人
                        getCustomerContactName(vo.customerCode);
                        $("#customerContactName").val(vo.customerContactName);
                        $('#contactEmail').val(vo.contactEmail);
                        $("#priceTermsCode").val(vo.priceTermsCode);
                        $("#currencyCode").val(vo.currencyCode);
                        $("#signingCompanyCode").val(vo.signingCompanyCode);
                        getBankInfo(vo.signingCompanyCode);
                        $('#bankCode').val(vo.bankCode);
                        $("#bankName").val(vo.bankName);
                        $('#bankAccount').val(vo.bankAccount);

                        //表单赋值
                        form.val("editor-form", {
                            "time" : vo.time,
                            "customerName" : vo.customerName,
                            "countryName" : vo.countryName,
                            "termOfValidity" : vo.termOfValidity,
                            "deliveryPeriod" : vo.deliveryPeriod,
                            "priceTermsName" : vo.priceTermsName,
                            "totalQuotation" : vo.totalQuotation,
                            "salesman" : vo.salesman,
                            "salesmanCode" : vo.salesmanCode,
                            "currency" : vo.currency,
                            "usdRate" : vo.usdRate,
                            "rmbRate" : vo.rmbRate,
                            "signingCompanyName" : vo.signingCompanyName,
                            "customerLevelCode" : vo.customerLevelCode,
                            "customerLevelName" : vo.customerLevelName,
                            "memo" : vo.memo
                        });

                        //报价产品明细数据
                        let detailList = res.data.detailList;
                        for(let i in detailList){
                            detailList[i]["tempId"] = detailList[i].id;
                            //获取对应配件数据
                            let tempPartList = detailList[i].partsList;
                            let partsList = [];
                            for(let j in tempPartList){
                                tempPartList[j]["parentTempId"] = detailList[i].id;
                                tempPartList[j]["tempId"] = tempPartList[j].id;
                                tempPartList[j]["id"] = null;
                                partsList.push(tempPartList[j]);
                            }
                            detailList[i]["partsList"] = partsList;
                            detailList[i]["id"] = null;
                            tempDetail.push(detailList[i]);
                        }

                        //费用数据
                        let costList = res.data.costList;
                        for(let k in costList){
                            costList[k]["tempId"] = costList[k].id;
                            costList[k]["id"] = null;
                            newCostList.push(costList[k]);
                        }

                        //附件
                        if(!isEmpty(res.data.annexList) && res.data.annexList.length > 0){
                            let tempAnnex = res.data.annexList;
                            for(let i in tempAnnex){
                                tempAnnex[i]["news"] = null;
                                tempAnnexList.push(tempAnnex[i]);
                            }
                        }

                    }
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    function setCustomerInfo(initData) {
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })

        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            $.ajax({
                url: "basicInformation/getCustomerInfo?info=" + obj.value,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        customerInfo = res.data.customerInfo;
                        for (let i in customerInfo) {
                            customerInfo[i]["value"] = customerInfo[i].code;
                            tempData.push(customerInfo[i]);
                        }
                    }
                }
            })
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            let name = obj.textContent;
            $("#customerCode").val(code);
            $("#customerName").val(name);
            //获取客户联系人
            getCustomerContactName(code);
            //获取客户等级
            $("#customerLevelName").val("");
            $("#customerLevelCode").val("");
            for(let i in customerInfo){
                if(customerInfo[i].code == code){
                    let customerLevelName = customerInfo[i]["customerLevelName"];
                    let customerLevelCode = customerInfo[i]["customerLevelCode"];
                    if(!isEmpty(customerLevelName)){
                        $("#customerLevelName").val(customerLevelName);
                        $("#customerLevelCode").val(customerLevelCode);
                        break;
                    }
                }
            }
        });
    }

    function getSelectData(){
        $.ajax({
            url: "otherOutStock/getAllUserInfo",
            async:false,
            success: function (data) {
                if (data.status == 200) {
                    salesmanInfo = data.data;
                    for (let i in salesmanInfo) {
                        $("#salesmanCode").append(new Option(salesmanInfo[i].name, salesmanInfo[i].code));
                    }
                }
            }
        });

        //获取国家信息
        $.ajax({
            url:"offer/getCountry",
            async:false,
            success:function(data){
                if(data.status == 200){
                    country = data.data;
                    for(let i in data.data){
                        $('#countryCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取价格术语信息
        $.ajax({
            url:"offer/getPriceTerms",
            async:false,
            success:function(data){
                if(data.status == 200){
                    priceTerms = data.data;
                    for(let i in data.data){
                        $('#priceTermsCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取币种
        $.ajax({
            url:"receivePayment/getCurrencyInfo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    currencyInfo = data.data;
                    for(let i in data.data){
                        if(data.data[i].englishName == "USD"){
                            //美元编码
                            usdCode = data.data[i].code;
                            //美元名称
                            usdName = data.data[i].name;
                            //获取美金兑人名币汇率
                            rmbRate = data.data[i].exchangeRate;

                            $("#rmbRate").val(rmbRate);
                        }else if(data.data[i].englishName == "RMB"){
                            //人名币兑美元汇率
                            usdRate = data.data[i].exchangeRate;
                        }
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取所有公司信息
        $.ajax({
            url:"receivePayment/getCompanyInfo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    companyInfo = data.data;
                    for(let i in data.data){
                        //公司名称
                        $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取数量单位
        $.ajax({
            url:"resourceSamples/getUnitOfQuantityInfo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    unitOfQuantity = data.data;
                }
            }
        });

        //获取海关编码信息
        $.ajax({
            url:"offer/getCustomsCode",
            async:false,
            success:function(data){
                if(data.status == 200){
                    customsCode = data.data;
                }
            }
        });

        //获取费用类型
        $.ajax({
            url:"offer/getCostType",
            async:false,
            success:function(data){
                if(data.status == 200){
                    costType = data.data;
                }
            }
        });

        //生成最新报价单号
        getNewBillNo();
    }

    //生成最新报价单号
    function getNewBillNo(){
        //生成最新报价单号
        let flag = false;
        $.ajax({
            url:"offer/getOfferBillNo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    //报价单号：BJ+yyyyMMdd+3位有序数字
                    let billNo = data.data;
                    $("#billNo").val(billNo);
                    flag = true;
                }else {
                    layer.msg(data.msg, {icon: 5});
                }
            }
        });
        return flag;
    }

    //监听业务员下拉框
    form.on("select(salesmanCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in salesmanInfo){
            if(data.value == salesmanInfo[i].code){
                $('#salesman').val(salesmanInfo[i].name);
                break;
            }
        }
    });

    function getCustomerContactName(customCode) {
        //通过客户编码获取客户联系人
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:customCode,
            url:"otherOutStock/add/getCustomerContactInfo",
            async:false,
            success:function(res){
                if(res.status == 200){
                    customerContact = res.data;
                    //客户联系人重新赋值
                    $("#customerContactName").empty();
                    for(let i in res.data){
                        $('#customerContactName').append(new Option(res.data[i].name, res.data[i].name));
                    }
                    form.render('select');
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    function getSalesman(code){
        for(let i in customerInfo){
            if(customerInfo[i].code == code){
                $('#salesmanCode').val(customerInfo[i].salesmanCode);
                $('#salesman').val(customerInfo[i].salesman);
                break;
            }
        }
    }

    //监听客户联系人下拉框
    form.on("select(customerContactName)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in customerContact){
            if(data.value == customerContact[i].name){
                $('#contactEmail').val(customerContact[i].email);
                form.render();
                break;
            }
        }
    });

    //监听价格术语下拉框
    form.on("select(priceTermsCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in priceTerms){
            if(data.value == priceTerms[i].code){
                $('#priceTermsName').val(priceTerms[i].name);
            }
        }
    });

    //监听币种下拉框
    form.on('select(currencyCode)', function (data) {
        if(data.value === ""){
            return;
        }
        let englishName = getCurrencyInfoByCode(data.value, 1);
        if(englishName == "RMB"){
            //如果选择rmb，则对应rmb汇率为1
            $("#rmbRate").val(1);
            $("#usdRate").val(usdRate);
        }else if(englishName == "USD"){
            //如果选择美元，则对应美金汇率为1
            $("#rmbRate").val(rmbRate);
            $("#usdRate").val(1);
        }else{
            //其它
            let exchangeRate = getCurrencyInfoByCode(data.value, 3);
            $("#usdRate").val(exchangeRate);
            $("#rmbRate").val(rmbRate);
        }
        let name = getCurrencyInfoByCode(data.value, 2);
        $("#currency").val(name);
    })

    //获取币种信息：code:编码  type(1:获取英文名称 2:获取name 3:获取汇率)
    function getCurrencyInfoByCode(code, type){
        for(let i in currencyInfo){
            if(currencyInfo[i].code == code){
                let res = "";
                switch (type) {
                    case 1:
                        res = currencyInfo[i].englishName;
                        break;
                    case 2:
                        res = currencyInfo[i].name;
                        break;
                    case 3:
                        res = currencyInfo[i].exchangeRate;
                        break;
                }
                return res;
            }
        }
        return "";
    }

    //监听签约公司下拉框
    form.on("select(signingCompanyCode)", function(data){
        if(data.value === ""){
            return;
        }
        let name = getCompanyInfoByCode(data.value);
        $("#signingCompanyName").val(name);
        //重新查询银行信息
        getBankInfo(data.value);
    });

    //监听收款银行名称下拉框
    form.on("select(bankCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in bankAccountList){
            if(data.value == bankAccountList[i].code){
                $("#bankName").val(bankAccountList[i].name);
                $("#bankAccount").val(bankAccountList[i].bankAccount);
                form.render('select');
                break;
            }
        }
    });

    //监听国家下拉框
    form.on("select(countryCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in country){
            if(country[i].code == data.value){
                $("#countryName").val(country[i].name);
                break;
            }
        }
    });


    //监听收款银行账号下拉框
    form.on("select(bankAccount)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in bankAccountList){
            if(data.value == bankAccountList[i].bankAccount){
                $("#bankCode").val(bankAccountList[i].code);
                $("#bankName").val(bankAccountList[i].name);
                form.render('select');
                break;
            }
        }
    });

    function getCompanyInfoByCode(code){
        for(let i in companyInfo){
            if(companyInfo[i].code == code){
                return companyInfo[i].name;
            }
        }
        return "";
    }

    function getBankInfo(code) {
        //获取银行账号
        $.ajax({
            url:"receivePayment/getBankAccountInfo?code=" + code,
            async:false,
            success:function(res){
                if(res.status == 200){
                    //银行信息
                    bankAccountList = res.data.bankAccountList;
                    $('#bankCode').empty();
                    $('#bankAccount').empty();
                    for(let i in bankAccountList){
                        $('#bankCode').append(new Option(bankAccountList[i].name, bankAccountList[i].code));
                        $('#bankAccount').append(new Option(bankAccountList[i].bankAccount, bankAccountList[i].bankAccount));
                    }
                    form.render('select');
                }
            }
        });
    }


    //监听提交
    form.on('submit(form-element)', function (data) {
        //防止重复提交问题
        preventDuplicateSubmissions();
        let indexsl = 0;
        //产品明细数据
        let storageproductsdata = table.cache["storageproductstableid"];
        //费用数据
        let costtabledata = table.cache["costtableid"];
        $.each(storageproductsdata, function (index, value) {
            if (typeof (storageproductsdata[index]["productNum"]) == "undefined" || storageproductsdata[index]["productNum"] == "") {
                layer.msg("产品表第" + (index + 1) + "条数量不能为空");
                indexsl++;
                return false;
            } else if (typeof (storageproductsdata[index]["unitPrice"]) == "undefined") {
                layer.msg("产品表第" + (index + 1) + "条单价不能为空");
                indexsl++;
                return false;
            } else if (typeof (storageproductsdata[index]["productUnitName"]) == "undefined" || storageproductsdata[index]["productUnitName"] == "" || storageproductsdata[index]["productUnitName"] == null) {
                storageproductsdata[index]["productUnitName"] = getProductUnitCode(storageproductsdata[index]["productUnitCode"]);
            }
            //配件数据
            let productsatabledata = storageproductsdata[index].partsList;
            if(typeof productsatabledata != "undefined" && productsatabledata != ""){
                $.each(productsatabledata, function (i, value) {
                    if (typeof (productsatabledata[i]["partsCode"]) == "undefined" || productsatabledata[i]["partsCode"] == "") {
                        layer.msg("产品表第" + (index + 1) + "条中对应产品规格配件表第" + (i + 1) + "条配件编码不能为空");
                        indexsl++;
                        return false;
                    } else if (typeof (productsatabledata[i]["proportionFinishedProducts"]) == "undefined" || productsatabledata[i]["proportionFinishedProducts"] == "") {
                        layer.msg("产品表第" + (index + 1) + "条中对应产品规格配件表第" + (i + 1) + "条成品比例不能为空");
                        indexsl++;
                        return false;
                    } else if (typeof (productsatabledata[i]["partsFinishedProducts"]) == "undefined" || productsatabledata[i]["partsFinishedProducts"] == "") {
                        layer.msg("产品表第" + (index + 1) + "条中对应产品规格配件表第" + (i + 1) + "条配件比例不能为空");
                        indexsl++;
                        return false;
                    }
                });
            }
            if(indexsl > 0){
                return false;
            }
        });
        if (indexsl == 0) {
            $.each(costtabledata, function (index, value) {
                if (typeof (costtabledata[index]["typeCode"]) == "undefined" || costtabledata[index]["typeCode"] == "") {
                    layer.msg("费用表第" + (index + 1) + "条费用类型不能为空");
                    indexsl++;
                    return false;
                } else if (typeof (costtabledata[index]["amount"]) == "undefined" || costtabledata[index]["amount"] == "") {
                    layer.msg("费用表第" + (index + 1) + "条金额不能为空");
                    indexsl++;
                    return false;
                }
            });
        }

        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        if (indexsl == 0) {
            req["detailList"] = storageproductsdata;

            req["costList"] = costtabledata;

            //获取附件数据
            let annexReqs = table.cache["attachmenttableid"];
            req["annexList"] = annexReqs;
            req["deleteAnnexIds"] = deleteAnnexIds;

            let datas = JSON.stringify(req);
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:datas,
                url:"offer/add",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/ExportBusiness/offer.jsp");
                            parent.intab("views/jsp/ExportBusiness/offer.jsp", "报价")
                            parent.detab("views/jsp/ExportBusiness/tpl/copyOffer.jsp" + (id == '' ? '' : '?id=' + id));
                        }, 1000);
                    }else {
                        if(res.status == 11005){
                            //单号已存在,需要生成新的单号
                            let flag = getNewBillNo();
                            if(flag){
                                layer.msg("单号已存在，已为您生成新的单号!", {icon: 6});
                            }else {
                                layer.msg("网络繁忙，请重新尝试！", {icon: 5});
                            }
                        }else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    }
                    return false;
                }
            });
        }
        return false;
    });

    //人名币汇率改变时，重载产品数据
    $("#rmbRate").keyup(function(){
        let rmbRate = $("#rmbRate").val();
        if(!isNumber(rmbRate)){
            layer.msg('请输入数字');
            return;
        }
        let tableData = table.cache["storageproductstableid"];
        //sum 金额小计
        let sumMoneySubtotal = 0;
        for(let i in tableData){
            //人名币汇率(人名币汇率变更，对应美金采购价、利润额、仓库费用金额、单价、金额小计、边际利润率重新计算)
            let purchasePriceRmb = tableData[i].purchasePriceRmb;
            if(checkNumber(rmbRate) && checkNumber(purchasePriceRmb)){
                //1.美金采购价:人民币采购价/人名币汇率
                let purchasePriceUsd = 0;
                if(0 != rmbRate){
                    purchasePriceUsd = new BigNumber(purchasePriceRmb).dividedBy(rmbRate).dp(4, BigNumber.ROUND_HALF_UP).toString();
                }
                tableData[i]["purchasePriceUsd"] = purchasePriceUsd;

                //2.利润额:数量*利润率*美金采购价*0.01
                let profitMargin = getProfitMargin(tableData[i]);
                tableData[i]["profitMargin"] = profitMargin;

                //3.仓库费用金额:仓库费用比*0.01*(美金采购价*(1+利润率*0.01)*1.3)*40HQ
                let warehouseCostAmount = getWarehouseCostAmount(tableData[i]);
                tableData[i]["warehouseCostAmount"] = warehouseCostAmount;

                //4.单价:
                let unitPrice = getPrice(tableData[i]);
                tableData[i]["unitPrice"] = unitPrice;

                //5.金额小计:单价*数量
                let moneySubtotal = getMoneySubtotal(tableData[i]);
                tableData[i]["moneySubtotal"] = moneySubtotal;
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);

                //6.边际利润率:利润额/金额小计*100
                let marginalProfitRatio = getMarginalProfitRatio(tableData[i]);
                tableData[i]["marginalProfitRatio"] = marginalProfitRatio;
            }
        }
        //报价总额=sum(金额小计)+sum(费用)
        //费用
        let costData = table.cache["costtableid"];
        let sumAmount = 0;
        for(let i in costData){
            let amount = costData[i].amount;
            if(!checkNumber(amount)){
                amount = 0;
            }
            sumAmount = new BigNumber(sumAmount).plus(amount);
        }
        let sum = new BigNumber(sumMoneySubtotal).plus(sumAmount).dp(4, BigNumber.ROUND_HALF_UP).toString();
        $("#totalQuotation").val(sum);
        table.reload('storageproductstableid',{data:tableData});
        form.render();
    });
    let initData = [];
//--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: initData,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'img', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'specificationExplanation', width: 120, title: '规格说明', edit: 'text'},
            {field: 'productCode', width: 220, title: '产品编码', templet: '#productcodeselect'},
            {field: 'specificationCode', width: 120, title: '规格编码', edit: 'text'},
            {field: 'productEname', width: 120, title: '英文名称', edit: 'text'},
            {field: 'productEdesc', width: 120, title: '英文描述', edit: 'text'},
            {field: 'productNum', width: 120, title: '数量', edit: 'text',style:"color:#009688", totalRow: true},
            {field: 'profitMarginRatio', width: 120, title: '利润率%', edit: 'text',style:"color:#009688"},
            {field: 'profitMargin', width: 120, title: '利润额', edit: 'text'},
            {field: 'marginalProfitRatio', width: 120, title: '边际利润率%', edit: 'text'},
            {field: 'unitPrice', width: 150, title: '单价', edit: 'text'},
            {field: 'moneySubtotal', width: 120, title: '金额小计', edit: 'text', totalRow: true},
            {field: 'purchasePriceUsd', width: 120, title: '美金采购价'},
            {field: 'purchasePriceRmb', width: 200, title: '人民币采购价（采购成本）', edit: 'text'},
            {field: 'warehouseCostRatio', width: 120, title: '仓库费用比%', edit: 'text'},
            {field: 'warehouseCostAmount', width: 120, title: '仓库费用金额', edit: 'text'},
            {field: 'fortyOceanFreight', width: 120, title: '40HQ海运费', edit: 'text'},
            {field: 'fortyHq', width: 120, title: '40HQ', edit: 'text'},
            {field: 'importTariffs', width: 120, title: '进口关税%', edit: 'text'},
            {field: 'taxRebateRate', width: 120, title: '退税率%', edit: 'text'},
            {field: 'productUnitCode', width: 120, title: '单位', templet: '#unitselect'},
            {field: 'color', width: 120, title: '颜色', edit: 'text'},
            {field: 'productCname', width: 120, title: '中文名称', edit: 'text'},
            {field: 'clientProductNo', width: 120, title: '客户货号', edit: 'text'},
            {field: 'customsCode', width: 320, title: '海关编码', templet: '#customscodeselect'},
            {field: 'nameCustomsDeclaration', width: 120, title: '报关品名', edit: 'text'},
            {field: 'customsDeclarationUnit', width: 120, title: '报关单位', edit: 'text'},
            {field: 'englishProductName', width: 120, title: '英文品名', edit: 'text'},
            {field: 'vatRate', width: 120, title: '增值税率%', edit: 'text'},
            {field: 'productCdesc', width: 120, title: '中文描述', edit: 'text'},
            {field: 'supplierName', width: 120, title: '供应商名称', edit: 'text'},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            hoverOpenImg();//显示大图

            //字段权限控制
            let roleFlag = user.code == "RKB005" || user.code == "RKB068" || user.code == "RKB003" || user.code == "RKB006" || user.code == "RKB010";
            if(!roleFlag){
                $("[data-field='purchasePriceRmb']").css('display','none');
                $("[data-field='purchasePriceUsd']").css('display','none');
                $("[data-field='profitMargin']").css('display','none');
                $("[data-field='warehouseCostRatio']").css('display','none');
                $("[data-field='fortyOceanFreight']").css('display','none');
                $("[data-field='marginalProfitRatio']").css('display','none');
                $("[data-field='warehouseCostAmount']").css('display','none');
                $("[data-field='profitMarginRatio']").css('display','none');
            }

            for(let i in customsCode){
                $(".customsCode").append("<option value=\"" + customsCode[i].code + "\">" + customsCode[i].code + "_" + customsCode[i].name + "</option>");
            }
            for(let i in unitOfQuantity){
                $(".productUnitCode").append("<option value=\"" + unitOfQuantity[i].code + "\">" + unitOfQuantity[i].name + "</option>");
            }

            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                let classs = ".y_" + tempId;
                $(classs).ySearchSelect(classs);
                if(!isEmpty(res.data[i].productUnitCode)){
                    $("#productUnitCode_" + tempId).val(res.data[i].productUnitCode);
                }else {
                    let unit = unitOfQuantity[0].code;
                    res.data[i].productUnitCode = unit;
                    $("#productUnitCode_" + tempId).val(unit);
                }

                //海关相关信息
                if(!isEmpty(res.data[i].customsCode)){
                    $("#customsCode_" + tempId).val(res.data[i].customsCode);
                }
                //金额小计
                let moneySubtotal = res.data[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }
            //sum(费用)
            let costData = table.cache["costtableid"];
            let sumAmount = 0;
            for(let i in costData){
                let amount = costData[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let totalQuotation = new BigNumber(sumMoneySubtotal).plus(sumAmount).dp(2, BigNumber.ROUND_HALF_UP).toString();
            $("#totalQuotation").val(totalQuotation);
            form.render('select');
        }
    });


    function checkNumber(val) {
        if(isEmpty(val)){
            return false;
        }
        if(!isNumber(val)){
            return false;
        }
        return true;
    }


    form.on("select(customscodeselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["customsCode"] = data.value;
                for(let i in customsCode){
                    if(customsCode[i].code == data.value){
                        //报关品名
                        tableData[index]["nameCustomsDeclaration"] = customsCode[i].name;
                        //英文品名
                        tableData[index]["englishProductName"] = customsCode[i].englishName;
                        //报关单位
                        tableData[index]["customsDeclarationUnit"] = customsCode[i].unitOfQuantity;
                        //进口关税
                        tableData[index]["importTariffs"] = customsCode[i].importTariff;
                        //退税率
                        tableData[index]["taxRebateRate"] = customsCode[i].taxRate;
                        //增值税率
                        tableData[index]["vatRate"] = customsCode[i].vatRate;
                    }
                }
            }
        });
        table.reload('storageproductstableid',{data:tableData});
    });
    form.on("select(unitselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["productUnitCode"] = data.value;
                tableData[index]["productUnitName"] = getProductUnitCode(data.value);
            }
        });
    });

    function getProductUnitCode(code){
        for(let i in unitOfQuantity){
            if(unitOfQuantity[i].code == code){
                return unitOfQuantity[i].name;
            }
        }
        return "";
    }

    //计算单价
    function getPrice(data){
        //单价=[美金采购价]*(1+[利润率(%)]*0.01)+
        // [仓库费用金额]/[40HQ]+
        // [40HQ海运费] /[40HQ]+
        // [进口关税]*0.01*(([美金采购价]*(1+[利润率(%)]*0.01)*1.3))-
        // [退税率]*0.01*[美金采购价]
        //美金采购价
        let purchasePriceUsd = data.purchasePriceUsd;
        if(!checkNumber(purchasePriceUsd)){
            purchasePriceUsd = 0;
        }
        //利润率(%)
        let profitMarginRatio = data.profitMarginRatio;
        if(!checkNumber(profitMarginRatio)){
            profitMarginRatio = 0;
        }
        //仓库费用金额
        let warehouseCostAmount = data.warehouseCostAmount;
        if(!checkNumber(warehouseCostAmount)){
            warehouseCostAmount = 0;
        }
        //40HQ
        let fortyHq = data.fortyHq;
        if(!checkNumber(fortyHq)){
            fortyHq = 0;
        }
        //40HQ海运费
        let fortyOceanFreight = data.fortyOceanFreight;
        if(!checkNumber(fortyOceanFreight)){
            fortyOceanFreight = 0;
        }
        //进口关税
        let importTariffs = data.importTariffs;
        if(!checkNumber(importTariffs)){
            importTariffs = 0;
        }
        //退税率
        let taxRebateRate = data.taxRebateRate;
        if(!checkNumber(taxRebateRate)){
            taxRebateRate = 0;
        }
        //四舍五入保留4位小数

        let stepOne = new BigNumber(profitMarginRatio).multipliedBy(0.01).plus(1).toString();
        let oneRow = new BigNumber(purchasePriceUsd).multipliedBy(stepOne).toString();

        let towRow = 0;
        if(0 != warehouseCostAmount){
            towRow = new BigNumber(warehouseCostAmount).dividedBy(fortyHq).toString();
        }

        let threeRow = 0;
        if(0 != fortyOceanFreight){
            threeRow = new BigNumber(fortyOceanFreight).dividedBy(fortyHq).toString();
        }

        let stepTwo = new BigNumber(purchasePriceUsd).multipliedBy(stepOne).multipliedBy(1.3).toString();
        let fourRow = new BigNumber(importTariffs).multipliedBy(0.01).multipliedBy(stepTwo).toString();

        let fiveRow = new BigNumber(taxRebateRate).multipliedBy(0.01).multipliedBy(purchasePriceUsd).toString();

        let sum = new BigNumber(oneRow).plus(towRow).plus(threeRow).plus(fourRow).minus(fiveRow);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //计算利润额:数量*利润率*美金采购价*0.01
    function getProfitMargin(data){
        //美金采购价
        let purchasePriceUsd = data.purchasePriceUsd;
        if(!checkNumber(purchasePriceUsd)){
            purchasePriceUsd = 0;
        }
        //利润率(%)
        let profitMarginRatio = data.profitMarginRatio;
        if(!checkNumber(profitMarginRatio)){
            profitMarginRatio = 0;
        }
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            productNum = 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(productNum).multipliedBy(profitMarginRatio).multipliedBy(purchasePriceUsd).multipliedBy(0.01);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //边际利润率:利润额/金额小计*100
    function getMarginalProfitRatio(data){
        //利润额
        let profitMargin = data.profitMargin;
        if(!checkNumber(profitMargin)){
            profitMargin = 0;
        }
        //金额小计
        let moneySubtotal = data.moneySubtotal;
        if(!checkNumber(moneySubtotal)){
            moneySubtotal = 0;
        }
        //四舍五入保留4位小数
        let sum = 0;
        if(0 != moneySubtotal){
            sum = new BigNumber(profitMargin).dividedBy(moneySubtotal).multipliedBy(100).dp(4, BigNumber.ROUND_HALF_UP).toString();
        }
        return sum;
    }

    //仓库费用金额:仓库费用比*0.01*(美金采购价*(1+利润率*0.01)*1.3)*40HQ
    function getWarehouseCostAmount(data){
        //仓库费用比
        let warehouseCostRatio = data.warehouseCostRatio;
        if(!checkNumber(warehouseCostRatio)){
            warehouseCostRatio = 0;
        }
        //美金采购价
        let purchasePriceUsd = data.purchasePriceUsd;
        if(!checkNumber(purchasePriceUsd)){
            purchasePriceUsd = 0;
        }
        //利润率
        let profitMarginRatio = data.profitMarginRatio;
        if(!checkNumber(profitMarginRatio)){
            profitMarginRatio = 0;
        }
        //40HQ
        let fortyHq = data.fortyHq;
        if(!checkNumber(fortyHq)){
            fortyHq = 0;
        }
        //四舍五入保留4位小数
        //1+利润率*0.01
        let stepOne = new BigNumber(profitMarginRatio).multipliedBy(0.01).plus(1).toString();
        //美金采购价*(1+利润率*0.01)*1.3
        let stepTwo = new BigNumber(purchasePriceUsd).multipliedBy(stepOne).multipliedBy(1.3).toString();

        let sum = new BigNumber(warehouseCostRatio).multipliedBy(0.01).multipliedBy(stepTwo).multipliedBy(fortyHq);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //金额小计:单价*数量
    function getMoneySubtotal(data){
        //单价
        let unitPrice = data.unitPrice;
        if(!checkNumber(unitPrice)){
            unitPrice = 0;
        }
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            productNum = 0;
        }

        let sum = new BigNumber(unitPrice).multipliedBy(productNum);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //报价总额:sum(金额小计)+sum(费用)
    function getTotalQuotation(data, currentData){
        let productData = table.cache["storageproductstableid"];
        //sum(金额小计)
        let sumMoneySubtotal = 0;
        for(let i in productData){
            if(productData[i].tempId == data.tempId){
                continue;
            }
            //金额小计
            let moneySubtotal = productData[i].moneySubtotal;
            if(!checkNumber(moneySubtotal)){
                moneySubtotal = 0;
            }
            sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
        }
        //sum(费用)
        let costData = table.cache["costtableid"];
        let sumAmount = 0;
        for(let i in costData){
            let amount = costData[i].amount;
            if(!checkNumber(amount)){
                amount = 0;
            }
            sumAmount = new BigNumber(sumAmount).plus(amount);
        }
        let sum = new BigNumber(sumMoneySubtotal).plus(sumAmount).plus(currentData).dp(4, BigNumber.ROUND_HALF_UP).toString();
        return sum;
    }

    function productTableReload(){
        /*table.reload('storageproductstableid',{
            data:table.cache.test,
            totalRow: true,
        })*/
    }

    table.on('edit(storageproductstable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "productNum" ||
            obj.field == "unitPrice" ||
            obj.field == "moneySubtotal" ||
            obj.field == "purchasePriceRmb" ||
            obj.field == "purchasePriceUsd" ||
            obj.field == "profitMargin" ||
            obj.field == "warehouseCostRatio" ||
            obj.field == "fortyOceanFreight" ||
            obj.field == "fortyHq" ||
            obj.field == "marginalProfitRatio" ||
            obj.field == "warehouseCostAmount" ||
            obj.field == "profitMarginRatio" ||
            obj.field == "importTariffs" ||
            obj.field == "taxRebateRate" ||
            obj.field == "vatRate") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.field == "purchasePriceRmb"){
            //人民币采购价(人民币采购价变更，对应美金采购价、利润额、仓库费用金额、单价、金额小计、边际利润率重新计算)
            let rmbRate = $("#rmbRate").val();
            let purchasePriceRmb = obj.value;
            if(checkNumber(rmbRate) && checkNumber(purchasePriceRmb)){
                //1.美金采购价:人民币采购价/人名币汇率
                let purchasePriceUsd = 0;
                if(0 != rmbRate){
                    purchasePriceUsd = new BigNumber(purchasePriceRmb).dividedBy(rmbRate).dp(4, BigNumber.ROUND_HALF_UP).toString();
                }
                obj.update({
                    purchasePriceUsd :  purchasePriceUsd
                });
                obj.data.purchasePriceUsd = purchasePriceUsd;

                //2.利润额:数量*利润率*美金采购价*0.01
                let profitMargin = getProfitMargin(obj.data);
                obj.update({
                    profitMargin :  profitMargin
                });
                obj.data.profitMargin = profitMargin;

                //3.仓库费用金额:仓库费用比*0.01*(美金采购价*(1+利润率*0.01)*1.3)*40HQ
                let warehouseCostAmount = getWarehouseCostAmount(obj.data);
                obj.update({
                    warehouseCostAmount :  warehouseCostAmount
                });
                obj.data.warehouseCostAmount = warehouseCostAmount;

                //4.单价:
                let unitPrice = getPrice(obj.data);
                obj.update({
                    unitPrice :  unitPrice
                });
                obj.data.unitPrice = unitPrice;

                //5.金额小计:单价*数量
                let moneySubtotal = getMoneySubtotal(obj.data);
                obj.update({
                    moneySubtotal :  moneySubtotal
                });
                obj.data.moneySubtotal = moneySubtotal;
                //报价总额
                let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
                $("#totalQuotation").val(totalQuotation);
                form.render();

                //6.边际利润率:利润额/金额小计*100
                let marginalProfitRatio = getMarginalProfitRatio(obj.data);
                obj.update({
                    marginalProfitRatio :  marginalProfitRatio
                });

                //表单重载
                productTableReload();
            }

        }
        if(obj.field == "purchasePriceUsd"){
            //美金采购价(美金采购价变更，对应利润额、仓库费用金额、单价、金额小计、边际利润率重新计算)
            let purchasePriceUsd = obj.value;
            obj.data.purchasePriceUsd = purchasePriceUsd;
            //1.利润额:数量*利润率*美金采购价*0.01
            let profitMargin = getProfitMargin(obj.data);
            obj.update({
                profitMargin :  profitMargin
            });
            obj.data.profitMargin = profitMargin;

            //2.仓库费用金额:仓库费用比*0.01*(美金采购价*(1+利润率*0.01)*1.3)*40HQ
            let warehouseCostAmount = getWarehouseCostAmount(obj.data);
            obj.update({
                warehouseCostAmount :  warehouseCostAmount
            });
            obj.data.warehouseCostAmount = warehouseCostAmount;

            //3.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //4.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //5.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "profitMargin"){
            //利润额(利润额变更，对应边际利润率重新计算)
            let profitMargin = obj.value;
            obj.data.profitMargin = profitMargin;

            //1.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });
        }
        if(obj.field == "warehouseCostAmount"){
            //仓库费用金额(仓库费用金额变更，对应单价、金额小计、边际利润率重新计算)
            let warehouseCostAmount = obj.value;
            obj.data.warehouseCostAmount = warehouseCostAmount;

            //1.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //2.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //3.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "unitPrice"){
            //单价(单价变更，对应金额小计、边际利润率重新计算)
            let unitPrice = obj.value;
            obj.data.unitPrice = unitPrice;

            //1.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //2.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "moneySubtotal"){
            //金额小计(金额小计变更，对应边际利润率重新计算)
            let moneySubtotal = obj.value;
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //1.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "productNum"){
            //数量(数量变更，对应利润额、金额小计、边际利润率、配件数量重新计算)
            let productNum = obj.value;
            obj.data.productNum = productNum;

            //1.利润额:数量*利润率*美金采购价*0.01
            let profitMargin = getProfitMargin(obj.data);
            obj.update({
                profitMargin :  profitMargin
            });
            obj.data.profitMargin = profitMargin;

            //2.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //3.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //4.配件数量:对应产品数量*配件比例
            let partsList = obj.data.partsList;
            if(!isEmpty(partsList) && partsList.length > 0){
                for(let i in partsList){
                    //配件比例
                    let partsFinishedProducts = partsList[i].partsFinishedProducts;
                    let sum = new BigNumber(productNum).multipliedBy(partsFinishedProducts).dp(4, BigNumber.ROUND_HALF_UP).toString();
                    partsList[i]["partsAmount"] = sum;
                }
            }
            //表单重载
            productTableReload();

            table.reload("productsatableid", {data: partsList});
        }
        if(obj.field == "profitMarginRatio"){
            //利润率(利润率变更，对应利润额、仓库费用金额、单价、金额小计、边际利润率重新计算)
            let profitMarginRatio = obj.value;
            obj.data.profitMarginRatio = profitMarginRatio;

            //1.利润额:数量*利润率*美金采购价*0.01
            let profitMargin = getProfitMargin(obj.data);
            obj.update({
                profitMargin :  profitMargin
            });
            obj.data.profitMargin = profitMargin;

            //2.仓库费用金额:仓库费用比*0.01*(美金采购价*(1+利润率*0.01)*1.3)*40HQ
            let warehouseCostAmount = getWarehouseCostAmount(obj.data);
            obj.update({
                warehouseCostAmount :  warehouseCostAmount
            });
            obj.data.warehouseCostAmount = warehouseCostAmount;

            //3.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //4.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //5.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "warehouseCostRatio"){
            //仓库费用比(仓库费用比变更，对应仓库费用金额、单价、金额小计、边际利润率重新计算)
            let warehouseCostRatio = obj.value;
            obj.data.warehouseCostRatio = warehouseCostRatio;

            //1.仓库费用金额:仓库费用比*0.01*(美金采购价*(1+利润率*0.01)*1.3)*40HQ
            let warehouseCostAmount = getWarehouseCostAmount(obj.data);
            obj.update({
                warehouseCostAmount :  warehouseCostAmount
            });
            obj.data.warehouseCostAmount = warehouseCostAmount;

            //2.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //3.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //4.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "fortyHq"){
            //40HQ(40HQ变更，对应仓库费用金额、单价、金额小计、边际利润率重新计算)
            let fortyHq = obj.value;
            obj.data.fortyHq = fortyHq;

            //1.仓库费用金额:仓库费用比*0.01*(美金采购价*(1+利润率*0.01)*1.3)*40HQ
            let warehouseCostAmount = getWarehouseCostAmount(obj.data);
            obj.update({
                warehouseCostAmount :  warehouseCostAmount
            });
            obj.data.warehouseCostAmount = warehouseCostAmount;

            //2.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //3.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //4.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "fortyOceanFreight"){
            //40HQ海运费(40HQ海运费变更，对应单价、金额小计、边际利润率重新计算)
            let fortyOceanFreight = obj.value;
            obj.data.fortyOceanFreight = fortyOceanFreight;

            //1.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //2.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //3.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "importTariffs"){
            //进口关税(进口关税变更，对应单价、金额小计、边际利润率重新计算)
            let importTariffs = obj.value;
            obj.data.importTariffs = importTariffs;

            //1.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //2.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //3.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }
        if(obj.field == "taxRebateRate"){
            //退税率(退税率变更，对应单价、金额小计、边际利润率重新计算)
            let taxRebateRate = obj.value;
            obj.data.taxRebateRate = taxRebateRate;

            //1.单价:
            let unitPrice = getPrice(obj.data);
            obj.update({
                unitPrice :  unitPrice
            });
            obj.data.unitPrice = unitPrice;

            //2.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //报价总额
            let totalQuotation = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalQuotation").val(totalQuotation);
            form.render();

            //3.边际利润率:利润额/金额小计*100
            let marginalProfitRatio = getMarginalProfitRatio(obj.data);
            obj.update({
                marginalProfitRatio :  marginalProfitRatio
            });

            //表单重载
            productTableReload();
        }

    });

    //产品明细单个删除
    table.on('tool(storageproductstable)', function (obj) {
        let data = obj.data;
        //校验如果下游(外销)导入了该产品，则不能删除
        if(!isEmpty(data.isDelete) && 1 == data.isDelete){
            layer.msg("删除失败，该产品已被调用！", {icon: 4});
            return;
        }
        let oldData =  table.cache["storageproductstableid"];
        if (obj.event === 'del') {
            layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                for(let i in oldData){
                    if(oldData[i].tempId == data.tempId){
                        oldData.splice(i, 1);
                        table.reload('storageproductstableid',{data : oldData});
                        let defData = [];
                        table.reload("productsatableid", {data: defData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    table.on('toolbar(storageproductstable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'importproducts':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/productlibraryimport.jsp?tableid=storageproductstableid&modelId=offer'
                });
                break;
            case 'new':
                let oldData = table.cache["storageproductstableid"];
                let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
                let newData = {
                    "tempId": tempId,
                    "productNum": 0,
                    "unitPrice" : 0,
                    "moneySubtotal" : 0,
                    "purchasePriceUsd" : 0,
                    "purchasePriceRmb" : 0,
                    "profitMargin" : 0,
                    "warehouseCostRatio" : 0,
                    "fortyOceanFreight" : 0,
                    "fortyHq" : 0,
                    "marginalProfitRatio" : 0,
                    "warehouseCostAmount" : 0,
                    "profitMarginRatio" : 0,
                    "importTariffs" : 0,
                    "taxRebateRate" : 0,
                    "isDelete" : 0,
                    "vatRate" : 0
                };
                oldData.push(newData);
                table.reload('storageproductstableid', {data: oldData, limit : oldData.length});
                tobottomfn("storageproductstableid");
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                let flag = false;
                data.forEach(function (n, i) {
                    //校验如果下游(外销)导入了该产品，则不能删除
                    if(0 == n.isDelete){
                        delList.push(n.tempId);
                    }else {
                        flag = true;
                    }
                });
                if (delList != '') {
                    layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                        let cbList = table.cache["storageproductstableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("storageproductstableid", {
                            data: cbList,
                        });
                        let defData = [];
                        table.reload("productsatableid", {data: defData});
                        if(flag){
                            layer.msg('删除成功，存在部分被调用产品无法删除！', {
                                icon: 1,
                                time: 5000
                            });
                        }else {
                            layer.msg('删除成功');
                        }
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            let img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    //监听行单击事件 配件表
    table.on('row(storageproductstable)', function (obj) {
        $("#hidden").show();
        partsParentTempId = obj.data.tempId;
        let initParts = [];
        if(!isEmpty(obj.data.partsList)){
            initParts = obj.data.partsList;
        }
        table.render({
            elem: '#productsaselect'
            , data: initParts
            , toolbar: '#productsatoolbar'
            , where: {id: obj.data.id} //查询的产品ID，条件
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'partsCode', title: '配件编码', edit: 'text'}
                , {field: 'specNo', title: '规格编码', edit: 'text'}
                , {field: 'proportionFinishedProducts', title: '成品比例', edit: 'text'}
                , {field: 'partsFinishedProducts', title: '配件比例', edit: 'text'}
                , {field: 'partsAmount', title: '数量'}
                , {field: 'productCname', title: '中文名称', edit: 'text'}
                , {field: 'productEname', title: '英文名称', edit: 'text'}
                , {field: 'grossWeight', title: '毛重', edit: 'text'}
                , {field: 'netWeight', title: '净重', edit: 'text'}
                , {field: 'bulk', title: '体积', edit: 'text'}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#productsaup', title: '操作'}
            ]]
            , id: 'productsatableid'
            ,page: false
            ,limit: Number.MAX_VALUE
            , height: 300
        });
    });

    table.on('edit(productsatable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "proportionFinishedProducts" ||
            obj.field == "partsFinishedProducts" ||
            obj.field == "partsAmount" ||
            obj.field == "grossWeight" ||
            obj.field == "netWeight" ||
            obj.field == "bulk") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        let parentTable = table.cache["storageproductstableid"];
        for(let k in parentTable){
            if(parentTable[k].tempId == partsParentTempId){
                let partsList = parentTable[k].partsList;
                let productNum = parentTable[k].productNum;
                for(let j in partsList){
                    if(partsList[j].tempId == obj.data.tempId){
                        if(obj.field == "partsFinishedProducts"){
                            //配件比例
                            partsList[j]["partsFinishedProducts"] = obj.value;
                            let sum = new BigNumber(productNum).multipliedBy(obj.value).dp(4, BigNumber.ROUND_HALF_UP).toString();
                            partsList[j]["partsAmount"] = sum;
                            break;
                        }
                        if(obj.field == "partsCode"){
                            //配件编码
                            partsList[j]["partsCode"] = obj.value;
                            break;
                        }
                        if(obj.field == "specNo"){
                            //规格编码
                            partsList[j]["specNo"] = obj.value;
                            break;
                        }
                        if(obj.field == "proportionFinishedProducts"){
                            //成品比例
                            partsList[j]["proportionFinishedProducts"] = obj.value;
                            break;
                        }
                        if(obj.field == "partsAmount"){
                            //数量
                            partsList[j]["partsAmount"] = obj.value;
                            break;
                        }
                        if(obj.field == "productCname"){
                            //中文名称
                            partsList[j]["productCname"] = obj.value;
                            break;
                        }
                        if(obj.field == "productEname"){
                            //英文名称
                            partsList[j]["productEname"] = obj.value;
                            break;
                        }
                        if(obj.field == "grossWeight"){
                            //毛重
                            partsList[j]["grossWeight"] = obj.value;
                            break;
                        }
                        if(obj.field == "netWeight"){
                            //净重
                            partsList[j]["netWeight"] = obj.value;
                            break;
                        }
                        if(obj.field == "bulk"){
                            //体积
                            partsList[j]["bulk"] = obj.value;
                            break;
                        }
                    }
                }
                parentTable[k]["partsList"] = partsList;
                table.reload("storageproductstableid", {data: parentTable});
                table.reload("productsatableid", {data: partsList});
                break;
            }
        }
    });

    //导入配件信息
    table.on('toolbar(productsatable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'new':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/productlibraryimport.jsp?tableid=productsatableid&modelId=offer&partsParentTempId='+partsParentTempId
                });
                break;
            case 'delet':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                        let cbList = table.cache["productsatableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        //删除对应配件信息
                        deleteProductParts(cbList);
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    //配件表单个删除
    table.on('tool(productsatable)', function (obj) {
        let data = obj.data;
        let oldData =  table.cache["productsatableid"];
        if (obj.event === 'productsade') {
            layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                for(let i in oldData){
                    if(oldData[i].tempId == data.tempId){
                        oldData.splice(i, 1);
                        break;
                    }
                }
                //删除对应配件信息
                deleteProductParts(oldData);
                layer.msg('删除成功');
                layer.close(index);
            });
        }
    });

    //删除对应配件信息
    function deleteProductParts(oldData){
        let parentTable = table.cache["storageproductstableid"];
        for(let k in parentTable){
            if(parentTable[k].tempId == partsParentTempId){
                parentTable[k]["partsList"] = oldData;
                break;
            }
        }
        table.reload("storageproductstableid", {
            data: parentTable
        });
        table.reload("productsatableid", {
            data: oldData
        });
    }

    //---费用
    let initCost = [];
    table.render({
        elem: '#cost'
        , data: initCost
        , toolbar: '#costtoolbar'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'typeCode', title: '费用类型', templet: '#costtypeselect'}
            , {field: 'amount', title: '金额', event: 'amount', edit: 'text'}
            , {field: 'memo', title: '备注说明', edit: 'text'}
        ]]
        , id: 'costtableid'
        , height: 380
        ,page: false
        ,limit: Number.MAX_VALUE
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            for(let i in costType){
                $(".typeCode").append("<option value=\"" + costType[i].code + "\">" + costType[i].name + "</option>");
            }
            //sum(费用)
            let sumAmount = 0;
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                $("#typeCode_" + tempId).val(res.data[i].typeCode);

                let amount = res.data[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }

            let productData = table.cache["storageproductstableid"];
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for(let i in productData){
                //金额小计
                let moneySubtotal = productData[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }
            //报价总额=sum(金额小计)+sum(费用)
            let totalQuotation = new BigNumber(sumMoneySubtotal).plus(sumAmount).dp(4, BigNumber.ROUND_HALF_UP).toString();
            $("#totalQuotation").val(totalQuotation);

            form.render('select');
            form.render();
        }
    });
    table.on('edit(costtable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "amount") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.field == "amount"){
            //重新计算报价总额
            let productData = table.cache["storageproductstableid"];
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for(let i in productData){
                //金额小计
                let moneySubtotal = productData[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }

            //sum(费用)
            let costData = table.cache["costtableid"];
            let sumAmount = 0;
            for(let i in costData){
                if(costData[i].tempId == obj.data.tempId){
                    continue;
                }
                let amount = costData[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let totalQuotation = new BigNumber(sumMoneySubtotal).plus(sumAmount).plus(obj.value).dp(4, BigNumber.ROUND_HALF_UP).toString();
            $("#totalQuotation").val(totalQuotation);
            form.render();
        }
    });
    form.on("select(costtypeselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["costtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["typeCode"] = data.value;
                tableData[index]["typeName"] = getTypeNameByCode(data.value);
            }
        });
    });

    function getTypeNameByCode(code){
        for(let i in costType){
            if(costType[i].code == code){
                return costType[i].name;
            }
        }
        return "";
    }

    function tobottomfn(id){
        let d=$("[lay-id='"+id+"'] .layui-table-main").get(0)
        let h=d.scrollHeight
        d.scrollTo(0,h)
    }

    table.on('toolbar(costtable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'new':
                let oldData = table.cache["costtableid"];
                let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
                let newData = {
                    "tempId" : tempId,
                    "typeCode" : "",
                    "amount" : 0,
                    "memo" : ""
                };
                oldData.push(newData);
                table.reload('costtableid', {data: oldData, limit:oldData.length});
                tobottomfn("costtableid");
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？',confirmInfo(3,6), function (index) {
                        var cbList = table.cache["costtableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("costtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });


    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {type:'checkbox',title: "全选" ,fixed: true},
            {field: 'fileName', event:'fileName', title: '文件名'}
            , {field: 'uploadTime', title: '上传日期', sort:true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: false
        , limit: Number.MAX_VALUE
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        //点击关闭刷新表格
                        table.reload('attachmenttableid', {data: annexList, limit: annexList.length});
                    }
                });
                break;
            case 'annexDel':
                let checkStatus = table.checkStatus(obj.config.id);
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.id);
                });
                if (delList != '') {
                    layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                        let cbList = annexList;
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                    if(0 == cbList[i]["news"]){
                                        //记录被删除的老的附件
                                        deleteAnnexIds.push(item);
                                    }
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        layer.msg('删除成功');
                        table.reload("attachmenttableid", {data: cbList});
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;

        };
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            if(0 == annexList[i]["news"]){
                                //记录被删除的老的附件
                                deleteAnnexIds.push(id);
                            }
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        } else if (obj.event === 'fileName') {
            onLineFile(data.filePath);
        }
    });

//---操作日志
    let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }


    //时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
    function getNowFormatDate(type) {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if(1 == type){
            let currentDate = year + separator + month + separator + strDate;
            return currentDate;
        }else if(2 == type){
            let second = date.getMilliseconds().toString();
            if(second.length < 3){
                if(second.length == 1){
                    second = "0" + "0" + second;
                }else {
                    second = "0" + second;
                }
            }
            let currentDate = year.toString() + month.toString() + strDate.toString() + second;
            return currentDate;
        }

    }
    let currentDate = getNowFormatDate(1);
    //报价有效期限
    laydate.render({
        elem: '#termOfValidity',
        value: currentDate,
        isInitValue: true
    });

    //报价时间
    laydate.render({
        elem: '#time',
        value: currentDate,
        btns: ['confirm']
    });


    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }


});

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

function checkNumber(val) {
    if(isEmpty(val)){
        return false;
    }
    if(!isNumber(val)){
        return false;
    }
    return true;
}

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

function setHSInfo(data){
    for(let j in customsCode){
        if(customsCode[j].code == data.customsCode){
            //报关品名
            data["nameCustomsDeclaration"] = customsCode[j].name;
            //英文品名
            data["englishProductName"] = customsCode[j].englishName;
            //报关单位
            data["customsDeclarationUnit"] = customsCode[j].unitOfQuantity;
            //进口关税
            data["importTariffs"] = customsCode[j].importTariff;
            //退税率
            data["taxRebateRate"] = customsCode[j].taxRate;
            //增值税率
            data["vatRate"] = customsCode[j].vatRate;

            return data;
        }
    }
}